const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let openid = wxContext.OPENID;
  let nonceStr = await cloud.callFunction({name: 'randomString',data:{len:32}}).result;
  let body = event.goodsName;
  let outTradeNo = 'LYJS' + new Date().getTime()+ Math.random().toString(12).substr(2,11);
  let totalFee = event.totalFee;
  let name = event.name;
  let date = Math.round(new Date()/1000);
  let envId = event.envId;
  console.log('nonceStr:'+nonceStr);
  // 写入云数据库数据
  let userOrder = await db.collection("userOrder").add({
    data:{
      openid: openid,
      status: 0,
      name: name,
      subject: body,
      date: date,
      totalFee: totalFee,
      orderid: outTradeNo,
    }
  });
  let res = await cloud.cloudPay.unifiedOrder({
    "body": body,
    "nonceStr": nonceStr,
    "outTradeNo": outTradeNo,
    "spbillCreateIp": "127.0.0.1",
    "subMchId": "1613296330",
    "totalFee": totalFee,
    "tradeType": "JSAPI",
    "envId": envId,
    "functionName": "payCallback"
  });
  return res
}